package manager.customer.service.impl;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import manager.auth.config.JwtProperties;
import manager.customer.service.CustomerAuthService;
import manager.customer.dao.CustomerMapper;
import manager.customer.vo.Customer;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;
import org.springframework.stereotype.Service;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.util.List;
@Service(value = "customerAuthService")
@EnableConfigurationProperties(JwtProperties.class)
public class CustomerAuthServiceImpl implements CustomerAuthService {
    @Autowired
    private CustomerMapper customerMapper;
    @Override
    public String authentication(String username, String password) {
        //首先校验用户名和密码，如果不正确就不需要生成token TODO
        String token="";
        try {
            Customer customer =new Customer();
            customer.setUsername(username);
            List<Customer> customerList = customerMapper.select(customer);
            if(customerList.size()==0){
                return null;
            }
            String currentPassword = BCrypt.hashpw(password, customerList.get(0).getSalt());
            if(!currentPassword.equals(customerList.get(0).getPassword())){
                return null;
            }
            //校验通过后生成token
            ClassPathResource classPathResource = new ClassPathResource("huaweishop.jks");
            KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "huaweishop".toCharArray());
            KeyPair keyPair = keyStoreKeyFactory.getKeyPair("huaweishop");
            RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
            token= Jwts.builder().claim("userId", customerList.get(0).getId())
                .claim("username", username)
                .claim("password",currentPassword)
                .setExpiration(DateTime.now().plusMinutes(30).toDate())
                .signWith(SignatureAlgorithm.RS256, privateKey)
                .compact();
        }catch (Exception e){
            e.printStackTrace();
        }
        return token;
    }
}
